package com.ebupt.migu.common.util;

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;

import java.io.Closeable;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author liuyangyang@e-byte.com
 * @description: TODO
 * @date 2024/3/30 7:56
 */
public class RedisLock implements AutoCloseable {

    private RedisTemplate redisTemplate;

    private String key;

    private String value;

    private int expireTime;

    public RedisLock(RedisTemplate redisTemplate, String key) {
        SimpleDateFormat simpleDateFormatTaskDay = new SimpleDateFormat("yyyyMMdd");
        String day = simpleDateFormatTaskDay.format(new Date());
        this.redisTemplate = redisTemplate;
        this.key = key + "_" + day + "_ON_PROCESSING";
        this.value = UUID.randomUUID().toString();
        this.expireTime = 1000 * 60 * 10;
    }

    public boolean getLock() {
        RedisCallback<Boolean> redisCallback = connection -> {
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            Expiration seconds = Expiration.seconds(expireTime);
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            byte[] redisValue = redisTemplate.getKeySerializer().serialize(value);
            Boolean result = connection.set(redisKey, redisValue, seconds, setOption);
            return result;
        };
        boolean execute = (boolean)redisTemplate.execute(redisCallback);
        return execute;
    }

    public boolean unLock() {
        StringBuffer sb = new StringBuffer();
        sb.append("if  redis.call(\"get\",KEYS[1]) == ARGV[1] then\n");
        sb.append("return redis.call(\"del\",KEYS[1])\n");
        sb.append("else \n");
        sb.append("return 0\n");
        sb.append("end");
        RedisScript of = RedisScript.of(sb.toString(), Boolean.class);
        List<String> keys = Arrays.asList(key);
        boolean execute = (boolean)redisTemplate.execute(of, keys, value);
        return execute;
    }

    /**
     * Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects
     * managed by the {@code try}-with-resources statement.
     *
     * <p>
     * While this interface method is declared to throw {@code
     * Exception}, implementers are <em>strongly</em> encouraged to declare concrete implementations of the
     * {@code close} method to throw more specific exceptions, or to throw no exception at all if the close operation
     * cannot fail.
     *
     * <p>
     * Cases where the close operation may fail require careful attention by implementers. It is strongly advised to
     * relinquish the underlying resources and to internally <em>mark</em> the resource as closed, prior to throwing the
     * exception. The {@code
     * close} method is unlikely to be invoked more than once and so this ensures that the resources are released in a
     * timely manner. Furthermore it reduces problems that could arise when the resource wraps, or is wrapped, by
     * another resource.
     *
     * <p>
     * <em>Implementers of this interface are also strongly advised to not have the {@code close} method throw
     * {@link InterruptedException}.</em>
     * <p>
     * This exception interacts with a thread's interrupted status, and runtime misbehavior is likely to occur if an
     * {@code
     * InterruptedException} is {@linkplain Throwable#addSuppressed suppressed}.
     * <p>
     * More generally, if it would cause problems for an exception to be suppressed, the {@code AutoCloseable.close}
     * method should not throw it.
     *
     * <p>
     * Note that unlike the {@link Closeable#close close} method of {@link Closeable}, this {@code close} method is
     * <em>not</em> required to be idempotent. In other words, calling this {@code close} method more than once may have
     * some visible side effect, unlike {@code Closeable.close} which is required to have no effect if called more than
     * once.
     * <p>
     * However, implementers of this interface are strongly encouraged to make their {@code close} methods idempotent.
     *
     * @throws Exception if this resource cannot be closed
     */
    @Override
    public void close() throws Exception {

    }
}
